package com.zzxy.spring.aspect;

import com.zzxy.spring.service.impl.UserServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author aven
 * @description: TODO
 */
public class MyBeanFactoryCglib {
    public static UserServiceImpl createUserService() {
        final UserServiceImpl userService = new UserServiceImpl();

        final MyAspect aspect = new MyAspect();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(userService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                Object obj = methodProxy.invokeSuper(o, objects);
                aspect.after();
                return obj;
            }
        });
        UserServiceImpl proxy = (UserServiceImpl) enhancer.create();
        return proxy;
    }

}
